//
//  WSIdentifyViewController.m
//  WisdomStar
//
//  Created by 谭飞 on 2018/10/30.
//  Copyright © 2018年 zhangliwen. All rights reserved.
//

#import "WSIdentifyViewController.h"
#import "TZImagePickerController.h"
#import "CategoryView.h"
#import "AddTeacherView.h"
#import "VerifyUploadView.h"
#import "SHPickerView.h"

#import "SHUploadFileManager.h"
#import "ACMediaManager.h"
#import "CourseService.h"
#import "MyService.h"
#import "WSIdentifyModel.h"

typedef NS_ENUM(NSUInteger, IdentifyType) {
    Teacher = 1,  // 教师
    organization  // 机构
};

@interface WSIdentifyViewController ()<TZImagePickerControllerDelegate>
// constraints
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topContentHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *stackViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentViewHeight;

// subviews
@property (weak, nonatomic) IBOutlet UIView *topCateView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIStackView *stackView1;
@property (weak, nonatomic) IBOutlet UIStackView *stackView2;
@property (weak, nonatomic) IBOutlet UIView *contentView;

@property (nonatomic, weak) CategoryView *chooseCateView; // 选择授课类别
@property (nonatomic, weak) AddTeacherView *addTeaView; // 添加老师
@property (nonatomic, weak) VerifyUploadView *IDCardFrontView; // 身份证正面
@property (nonatomic, weak) VerifyUploadView *IDCardReverseView; // 身份证反面
@property (nonatomic, weak) VerifyUploadView *licenseView;  // 营业执照
@property (nonatomic, weak) VerifyUploadView *certificateView; // 其他证书

@property (nonatomic, strong) NSMutableArray *selectImages;
@property (nonatomic, strong) NSArray *cateList;

// 认证类型
@property (nonatomic, assign) IdentifyType type;
@property (nonatomic, copy) NSString *cate_id; // 课程类别id
@property (nonatomic, assign) NSInteger selectIndex;

@end

@implementation WSIdentifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self ws_setup];
    [self ws_loadData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    NSInteger count = self.type == Teacher ? 3 : 4;
    CGFloat padding = self.type == Teacher ? 20.f : 30.f;
    self.topContentHeight.constant = self.type == Teacher ? 60.f : 120.f;
    self.stackViewHeight.constant = self.IDCardFrontView.xmg_height * count + padding;
    self.contentViewHeight.constant = self.topContentHeight.constant + self.stackViewHeight.constant + 10.f;
    self.scrollView.contentSize = CGSizeMake(0, self.contentView.xmg_height);
}

#pragma mark - Override

- (void)ws_setup {
    self.type = Teacher; // 默认教师认证
    self.topCateView.layer.cornerRadius = self.topCateView.xmg_height/2;
    [self.topCateView setRoundBorder:kSeparatorColor radius:self.topCateView.xmg_height/2];
    
    // stackview
    self.stackView1.axis = UILayoutConstraintAxisVertical;
    self.stackView1.distribution = UIStackViewDistributionFillEqually;
    self.stackView1.spacing = 0.f;
    self.stackView1.alignment = UIStackViewAlignmentFill;
    
    self.stackView2.axis = UILayoutConstraintAxisVertical;
    self.stackView2.distribution = UIStackViewDistributionFillEqually;
    self.stackView2.spacing = 10.f;
    self.stackView2.alignment = UIStackViewAlignmentFill;
    
    // add subviews
    CategoryView *cateView = [CategoryView viewFromXib];
    self.chooseCateView = cateView;
    [self.stackView1 addArrangedSubview:cateView];
    
    AddTeacherView *addTeaView = [AddTeacherView viewFromXib];
    self.addTeaView = addTeaView;
    [self.stackView1 addArrangedSubview:addTeaView];
    
    VerifyUploadView *view1 = [VerifyUploadView viewFromXib];
    self.IDCardFrontView = view1;
    view1.icon = WSImageMake(@"img_idcardzm");
    [self.stackView2 addArrangedSubview:view1];
    
    VerifyUploadView *view2 = [VerifyUploadView viewFromXib];
    self.IDCardReverseView = view2;
    view2.icon = WSImageMake(@"img_idcardbm");
    [self.stackView2 addArrangedSubview:view2];
    
    VerifyUploadView *view3 = [VerifyUploadView viewFromXib];
    self.licenseView = view3;
    view3.title = @"上传机构营业执照";
    view3.icon = WSImageMake(@"img_yyzz");
    [self.stackView2 addArrangedSubview:view3];
    
    VerifyUploadView *view4 = [VerifyUploadView viewFromXib];
    self.certificateView = view4;
    view4.title = @"上传资格证/学历/获奖证书";
    view4.icon = WSImageMake(@"img_yyzz");
    [self.stackView2 addArrangedSubview:view4];
    [self updateUIContent];
    
    WEAKSELF
    
    /// 选择认证类型
    [self.topCateView addGestureWithGestureType:WJ_TapGesture completeHandler:^{
        UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"教师认证" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            weakSelf.titleLabel.text = action.title;
            weakSelf.type = Teacher;
            [weakSelf updateUIContent];
            [weakSelf.view layoutIfNeeded];
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"机构认证" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            weakSelf.titleLabel.text = action.title;
            weakSelf.type = organization;
            [weakSelf updateUIContent];
            [weakSelf.view layoutIfNeeded];
        }];
        [alertCtrl addAction:cancleAction];
        [alertCtrl addAction:action1];
        [alertCtrl addAction:action2];
        [self presentViewController:alertCtrl animated:YES completion:nil];
    }];

    /// 选择授课类别
    self.chooseCateView.didSelectedCallback = ^(UILabel * _Nonnull label) {
        NSMutableArray *items = [NSMutableArray arrayWithCapacity:weakSelf.cateList.count];
        [weakSelf.cateList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [items addObject:obj[@"name"]];
        }];
        SHPickerView *pickerView = [[SHPickerView alloc] initWithTitle:@"授课类别" items:items block:^(SHPickerView *pickerView, NSInteger selectRow) {
            label.text = items[selectRow];
            weakSelf.cate_id = weakSelf.cateList[selectRow][@"id"];
        }];
        [pickerView show];
    };
    
    /// 添加教师
    self.addTeaView.addHandleCallback = ^{
        
    };
    
    /// 上传图片
    self.IDCardFrontView.didUploadCallback = ^{
        weakSelf.selectIndex = 1;
        [weakSelf openAlbum];
    };
    
    self.IDCardReverseView.didUploadCallback = ^{
        weakSelf.selectIndex = 2;
        [weakSelf openAlbum];
    };
    
    self.licenseView.didUploadCallback = ^{
        weakSelf.selectIndex = 3;
        [weakSelf openAlbum];
    };
    
    self.certificateView.didUploadCallback = ^{
        weakSelf.selectIndex = 4;
        [weakSelf openAlbum];
    };
}

- (void)ws_loadData {
    [CourseService fetchCourseCateWithResult:^(id  _Nonnull responseObj) {
        ResponseModel *response = [ResponseModel yy_modelWithJSON:responseObj];
        if (!response.data) {
            return;
        }
        NSMutableArray *cateArr = [NSMutableArray array];
        [response.data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [cateArr addObject:obj];
        }];
        self.cateList = [cateArr copy];
    }];

}

#pragma mark - 提交认证

- (IBAction)commit:(id)sender {
    if (self.type == Teacher) { // 教师认证
        if (!self.cate_id) {
            [self showHint:@"请选择课程类别"];
            return;
        }
        if (!self.IDCardFrontView.image) {
            [self showHint:@"请上传身份证正面照片"];
            return;
        }
        if (!self.IDCardReverseView.image) {
            [self showHint:@"请上传身份证反面照片"];
            return;
        }
        if (!self.certificateView.image) {
            [self showHint:@"请上传资格证书"];
            return;
        }
        
        __block NSString *imageStr1, *imageStr2, *imageStr3;
        dispatch_group_t group = dispatch_group_create();
        
        [SVProgressHUD showLoading:@"请稍后..."];
        
        dispatch_group_enter(group);
        [SHUploadFileManager uploadWithImage:self.IDCardFrontView.image token:QNToken completion:^(NSString *result) {
            imageStr1 = [NSString stringWithFormat:@"%@/%@",[TFUserDefault valueForKey:@"imageUrl"], result];
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [SHUploadFileManager uploadWithImage:self.IDCardReverseView.image token:QNToken completion:^(NSString *result) {
            imageStr2 = [NSString stringWithFormat:@"%@/%@",[TFUserDefault valueForKey:@"imageUrl"], result];
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [SHUploadFileManager uploadWithImage:self.certificateView.image token:QNToken completion:^(NSString *result) {
            imageStr3 = [NSString stringWithFormat:@"%@/%@",[TFUserDefault valueForKey:@"imageUrl"], result];
            dispatch_group_leave(group);
        }];
        
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            dic[@"token"] = User_Token;
            dic[@"identy_z"] = imageStr1;
            dic[@"identy_f"] = imageStr2;
            dic[@"certificate"] = imageStr3;
            dic[@"real_name"] = @"张三";
            dic[@"cate"] = self->_cate_id;
            dic[@"type"] = @(self->_type);
            [MyService commitVerifyRequestWithType:self.type params:dic completion:^(BOOL success, id  _Nonnull responseObj) {
                if (success) {
                    [SVProgressHUD dismiss];
                    [self performSegueWithIdentifier:@"VerifyResult" sender:nil];
                }
            }];
        });
    }
}


#pragma mark - Utils

- (void)updateUIContent {
    self.addTeaView.hidden = self.type == Teacher;
    self.licenseView.hidden = self.type == Teacher;
    self.IDCardFrontView.title = self.type == Teacher ? @"上传本人身份证正面" : @"上传法人身份证正面";
    self.IDCardReverseView.title = self.type == Teacher ? @"上传本人身份证背面" : @"上传法人身份证背面";
}

/** 相册 */
- (void)openAlbum {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    ///是否 在相册中显示拍照按钮
    imagePickerVc.allowTakePicture = YES;
    ///是否可以选择显示原图
    imagePickerVc.allowPickingOriginalPhoto = NO;
    ///是否 在相册中可以选择视频
    imagePickerVc.allowPickingVideo = NO;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


#pragma mark - TZImagePickerController Delegate
//处理从相册单选或多选的照片
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    for (NSInteger index = 0; index < assets.count; index++) {
        PHAsset *asset = assets[index];
        [ACMediaManager getMediaInfoFromAsset:asset completion:^(NSString *name, id pathData) {
            if (index == assets.count - 1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (self.type == Teacher) {
                        switch (self->_selectIndex) {
                            case 1:
                                self.IDCardFrontView.image = photos[index];
                                self.IDCardFrontView.isHideIcon = YES;
                                break;
                            case 2:
                                self.IDCardReverseView.image = photos[index];
                                self.IDCardReverseView.isHideIcon = YES;
                                break;
                            case 4:
                                self.certificateView.image = photos[index];
                                self.certificateView.isHideIcon = YES;
                                break;
                        }
                        
                    } else {
                        switch (self->_selectIndex) {
                            case 1:
                                self.IDCardFrontView.image = photos[index];
                                self.IDCardFrontView.isHideIcon = YES;
                                break;
                            case 2:
                                self.IDCardReverseView.image = photos[index];
                                self.IDCardReverseView.isHideIcon = YES;
                                break;
                            case 3:
                                self.licenseView.image = photos[index];
                                self.licenseView.isHideIcon = YES;
                                break;
                            case 4:
                                self.certificateView.image = photos[index];
                                self.certificateView.isHideIcon = YES;
                                break;
                        }
                    }
                });
            }
        }];
    }
}


#pragma mark - Getter

- (NSMutableArray *)selectImages {
    if (_selectImages == nil) {
        _selectImages = [NSMutableArray array];
    }
    return _selectImages;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
